#!/usr/bin/env python
# -*-*- encoding: utf-8 -*-*-
#
# Copyright 2010 Håvard Gulldahl
# License: GPLv2

import sys, getpass, logging, os.path, mimetypes

import atom
import gdata.photos, gdata.media
import gdata.photos.service

gdata.photos.service.SUPPORTED_UPLOAD_TYPES += ('mp4',)

__license__ = "GPLv2"
__author__ = "<havard@gulldahl.no>"
__version__ = "0.1"
__doc__ = """Copy one or more picture or movie files to your account

Usage:
%s [-d] [albumname] <files>

The -d switch enables debug messages (Beware! This may reveal secrets.)
""" % sys.argv[0]

class quikalbum(object):
  titles = []
  ids = []
  checksums = []
  exifsums = []
  exifdates = []
  def __init__(self, album):
    for entry in album.entry:
      self.titles.append(entry.title.text)
      self.ids.append(entry.id.text)
      self.checksums.append(entry.checksum.text)
  def hasTitle(self, entry):
    return entry.title.text in self.titles
  def hasId(self, entry):
    return entry.id.text in self.ids
  def hasChecksum(self, entry):
    return entry.checksum.text in self.checksums

class copier(object):
  failed = []

  def __init__(self, user=None, password=None):
    self.user = user or raw_input("Enter picasaweb username")
    self.picasa = gdata.photos.service.PhotosService(
        email=self.user,
        password=password or getpass.getpass('Enter password for %s: ' % self.user),
        source='lurtgjort.no-PicasaPush/picasacopy-0.1')
    self.picasa.ProgrammaticLogin()

    self.albums = self.picasa.GetUserFeed(kind='album')

  def getAlbum(self, albumname):
    for i, album in enumerate(self.albums.entry):
      logging.debug("album; '%s' - id: %s", album.title.text, album.gphoto_id.text)
      if album.title.text == albumname:
        return album # found already existing album
    logging.debug("album does not already exist. must create it")
    album = self.picasa.InsertAlbum(title=albumname, summary="Created by picasamachine")
    logging.debug("created album online: %s", album)
    return album

  def copy(self, filename, albumname=None):

    if albumname is None:
      albumurl = '/data/feed/api/user/default/albumid/default'
    else:
      albumurl = self.getAlbum(albumname).GetPhotosUri()
    logging.debug("Target is album: %s", albumurl)
    
    numphotos = len(files)
    logging.info("About to copy %i images" % numphotos)

    self.failed = []

    keywords = gdata.media.Group(keywords=gdata.media.Keywords(text="no humans were involved"))
    entry = None
    
    for i, f in enumerate(files):
      try:
        mtype, mencoding = mimetypes.guess_type(f)
        entry = gdata.photos.PhotoEntry(title=atom.Title(text=os.path.basename(f)), media=keywords)
        logging.info("Copying photo %s: %s (%s)", i, entry.title.text, mtype)
        newphoto = self.picasa.InsertPhoto(albumurl, entry, open(f), content_type=mtype)
        yield ( float(i+1)/float(numphotos), newphoto )
      except Exception, (err):
        logging.error("Copying %s FAILED: %s", i, str(err))
        self.failed.append(f)
    logging.info("The transfer of the '%s' album is finished." % albumname)
    if self.failed:
      logging.error("%i images failed:", len(self.failed))
      for photo in self.failed:
        logging.error("%s", os.path.basename(photo))
      logging.debug("Programmers: Take a look at .failed[] to get the failed photos")

if __name__ == '__main__':
  DEBUG=False
  if "-d" in sys.argv:
    DEBUG=True
    sys.argv.remove('-d')

  if DEBUG:
    import httplib
    httplib.HTTPConnection.debuglevel=1  ## verbosely output http traffic
    logging.basicConfig(level=logging.DEBUG)
  else:
    logging.basicConfig(level=logging.INFO)

  album = None
  try:
    files = sys.argv[1:]
    if not os.path.exists(files[0]):
      album = files.pop(0)
  except IndexError:
    logging.error("Required arguments missing")
    print __doc__
    sys.exit(1)
  cont = 'y' # run the loop at least once
  try:
    f = open("/home/havard/.picasadevpass")
    u = f.readline()
    p = f.readline()
    f.close()
  except:
    u = p = None
  copymachine = copier(user=u, password=p)
  #while(not 'n' in cont):
  for progress, photo in copymachine.copy(files, album):
    logging.info("%i%%: %s copied", progress*100, photo.title.text)
    #cont = raw_input('Do you want to copy another album? [Y/n]').strip().lower()



